import { useEffect, useId, useMemo, useRef, useState } from 'react'
import { useMemoizedFn } from 'ahooks'
import _ from 'lodash'
import {
  Anchor,
  Badge,
  Button,
  Divider,
  Drawer,
  Form,
  FormProps,
  Input,
  message,
  Modal,
  Popconfirm,
  Radio,
  Space,
  Switch,
  Tooltip,
} from 'antd'
import Icon, { DeleteOutlined } from '@ant-design/icons'

import { CusTable } from '@/components/CusTable'
import { Loading } from '@/components/Loading'
import { useFormAllValues } from '@/hooks/hooks'
import { formAutoTrimOnBlur } from '@/utils/utils'
import { RouteTplShow } from '@oBiz/components/FieldShowComponents'
import { ITplRouteListItem, RouteTemplateListModal } from '@oBiz/components/RouteTemplateListModal'
import {
  getBooleanName,
  getLogisticsStatusName,
  getRouteNodeName,
  getRouteTypeName,
} from '@oBiz/components/RouteTemplateListModal/utils'
import { apiGetDetail, apiPostMsgManageAdd, apiUpdateMsgList } from '../apis'
import { mailOptions } from '../const'
import { EmailbodyPreviewModal } from '../EmailbodyPreviewModal'
import { IFormValues, IRoute, ISendValues, ITemplate } from '../interface'
import { MailTemplateListModal } from '../MailTemplateListModal'
import { createInitialFormValues, popupSlot, textInputFields } from '../utils'
import PrviewMailIcon from '@/assets/icons/prviewMail.svg?react'
import styles from './styles.module.less'
const updatePopup = popupSlot.insert(null)

interface IAddOrEditMsgDrawerProps {
  messageId?: string | null | undefined
  onSuccess?: () => void
}

export const AddOrEditMsgDrawer = Object.assign(
  ({ messageId, onSuccess, destroy }: IAddOrEditMsgDrawerProps & { destroy: () => void }) => {
    const { open, onHide, afterOpenChange } = popupSlot.useAntdPopupAnimation(destroy)
    const [loading, setLoading] = useState<boolean>(false)
    const [submitting, setSubmitting] = useState(false)
    const typeName = messageId ? '编辑' : '新建'
    const actionName = messageId ? '保存' : '新建'
    const idPrefix = useId()
    const scrollRef = useRef<HTMLDivElement>(null)
    const [form] = Form.useForm<IFormValues>()
    const initialFormValues = useMemo(() => createInitialFormValues(null), [])
    const allValues = useFormAllValues(form, initialFormValues)

    // form参数
    const formProps: FormProps<IFormValues> = {
      form,
      scrollToFirstError: { block: 'center', behavior: 'smooth' },
      layout: 'vertical',
      disabled: false,
      preserve: true,
      initialValues: initialFormValues,
      onBlur: e => formAutoTrimOnBlur({ event: e, form, includeField: textInputFields }),
    }

    // 编辑获取消息详情
    useEffect(() => {
      if (!messageId) return
      setLoading(true)
      apiGetDetail(messageId)
        .then(res => {
          const initRes = { ...res, templateList: [res.templateInfo] }
          form.setFieldsValue(createInitialFormValues(initRes))
        })
        .finally(() => {
          setLoading(false)
        })
    }, [form, messageId])

    // 基础信息
    const formRender0 = () => {
      return (
        <Form {...formProps}>
          <Form.Item style={{ width: '50%' }} label="标题" name="title" rules={[{ required: true }]}>
            <Input placeholder="请输入" allowClear />
          </Form.Item>
          <Form.Item label="类型" name="type" rules={[{ required: true }]}>
            <Radio.Group>
              <Radio value={1}>状态更新类</Radio>
              <Radio disabled value={2}>
                消息通知类（待开发）
              </Radio>
              <Radio disabled value={3}>
                营销通知类（待开发）
              </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="接受对象" name="receiveObj" rules={[{ required: true }]}>
            <Radio.Group>
              <Radio value={1}>客户联系人</Radio>
              <Radio disabled value={2}>
                系统员工（待开发）
              </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="状态（是否启用）" htmlFor={undefined} name="enableFlag" rules={[{ required: true }]}>
            <Switch />
          </Form.Item>
        </Form>
      )
    }

    // 触发事件
    const formRender1 = () => {
      return (
        <Form {...formProps}>
          <Form.Item label="触发条件" name="eventType" rules={[{ required: true }]}>
            <Radio.Group>
              <Radio value={1}>发布路由</Radio>
              <Radio value={2}>发布自定义邮件</Radio>
            </Radio.Group>
          </Form.Item>
          {allValues.eventType === 1 && (
            <Form.Item label="关联发布路由" required>
              <Button
                style={{ position: 'absolute', right: 0, top: -8, transform: 'translateY(-100%)' }}
                type="primary"
                onClick={() => {
                  RouteTemplateListModal.open({
                    title: '添加路由绑定',
                    onSuccess: (routeList: ITplRouteListItem[]) => {
                      const newRouteList = _.uniqBy([...routeList, ...allValues.messageRouteList], 'routeId')
                      form.setFieldsValue({ messageRouteList: newRouteList as IRoute[] })
                    },
                  })
                }}
              >
                添加关联
              </Button>
              <CusTable
                size="small"
                locale={{ emptyText: '暂无数据' }}
                rowKey={(...[{ routeId }, index]) => `${routeId}_${index}`}
                dataSource={allValues.messageRouteList}
                columns={[
                  {
                    title: '路由编号',
                    width: 100,
                    render: (_v, { routeNo }) => routeNo,
                  },
                  {
                    title: '中文模板',
                    width: 100 * 2,
                    render: (_v, { templateCn }) => {
                      return (
                        <div className={styles.template}>
                          <RouteTplShow value={templateCn} />
                        </div>
                      )
                    },
                  },
                  {
                    title: '英文模板',
                    width: 100 * 2,
                    render: (_v, { templateEn }) => {
                      return (
                        <div className={styles.template}>
                          <RouteTplShow value={templateEn} />
                        </div>
                      )
                    },
                  },
                  {
                    title: '节点',
                    width: 100,
                    render: (_v, { routeNode }) => getRouteNodeName(routeNode),
                  },
                  {
                    title: '物流状态',
                    width: 82,
                    render: (_v, { logisticsStatus }) => getLogisticsStatusName(logisticsStatus),
                  },
                  {
                    title: '路由类型',
                    width: 82,
                    render: (_v, { routeType }) => {
                      return <Badge color={routeType === 1 ? 'green' : 'red'} text={getRouteTypeName(routeType)} />
                    },
                  },
                  {
                    title: '需跟进',
                    width: 68,
                    render: (_v, { actionFlag }) => getBooleanName(actionFlag),
                  },
                  {
                    title: '客户可见',
                    width: 82,
                    render: (_v, { visibleFlag }) => getBooleanName(visibleFlag),
                  },
                  {
                    title: '操作',
                    width: 54,
                    minWidth: 54,
                    fixed: 'right',
                    render: (_v, _r, index) => {
                      return (
                        <Popconfirm
                          title="确定要删除吗"
                          onConfirm={() => {
                            const newList = [...allValues.messageRouteList]
                            newList.splice(index, 1)
                            form.setFieldValue('messageRouteList', newList)
                          }}
                        >
                          <Button type="link" danger icon={<DeleteOutlined />} />
                        </Popconfirm>
                      )
                    },
                  },
                ]}
              />
            </Form.Item>
          )}
          <Form.Item label="邮件发送时机" name="sendType" rules={[{ required: true }]}>
            <Radio.Group>
              <Radio value={1}>手动发送</Radio>
              <Radio value={2} disabled>
                定时发送
              </Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      )
    }

    // 通知渠道
    const formRender2 = () => {
      return (
        <Form {...formProps}>
          <Form.Item label="渠道" name="channelType" rules={[{ required: true }]}>
            <Radio.Group>
              {mailOptions.map((item, index) => {
                return (
                  <Radio key={index} value={item.value} disabled={item.disabled}>
                    {item.label}
                  </Radio>
                )
              })}
            </Radio.Group>
          </Form.Item>
          <Form.Item label="关联邮件模板" required>
            <Button
              style={{ position: 'absolute', right: 0, top: -8, transform: 'translateY(-100%)' }}
              type="primary"
              onClick={() => {
                MailTemplateListModal.open({
                  onSuccess: (templateList: ITemplate[]) => {
                    form.setFieldsValue({ templateList })
                  },
                })
              }}
            >
              添加关联
            </Button>
            <CusTable
              size="small"
              locale={{ emptyText: '暂无数据' }}
              rowKey={(...[{ templateId }, index]) => `${templateId}_${index}`}
              dataSource={allValues.templateList}
              columns={[
                {
                  title: '模板ID',
                  width: 100,
                  render: (_v, { templateId }) => templateId,
                },
                {
                  title: '模板标题',
                  width: 100 * 2.5,
                  render: (_v, { title }) => title,
                },
                {
                  title: '模板类型',
                  width: 100,
                  render: (_v, { type }) => type,
                },
                {
                  title: '操作',
                  width: 90,
                  minWidth: 90,
                  fixed: 'right',
                  render: (_v, { title, templateId, htmlBody }, index) => {
                    return (
                      <>
                        <Tooltip title="邮件正文模版预览">
                          <Button
                            type="link"
                            icon={
                              <Icon
                                component={PrviewMailIcon}
                                onClick={() => {
                                  const update = popupSlot.insert(
                                    <EmailbodyPreviewModal
                                      title={title || templateId}
                                      templateId={templateId}
                                      htmlBody={htmlBody}
                                      destroy={() => update(null)}
                                    />,
                                  )
                                }}
                              />
                            }
                          />
                        </Tooltip>
                        <Popconfirm
                          title="确定要删除吗？"
                          onConfirm={() => {
                            const newList = [...allValues.templateList]
                            newList.splice(index, 1)
                            form.setFieldValue('templateList', newList)
                          }}
                        >
                          <Button type="link" danger icon={<DeleteOutlined />} />
                        </Popconfirm>
                      </>
                    )
                  },
                },
              ]}
            />
          </Form.Item>
        </Form>
      )
    }

    const submitHandler = useMemoizedFn(async () => {
      form.submit() // 触发 scrollToFirstError
      let values = await form.validateFields()
      values = form.getFieldsValue(true)
      if (values.eventType === 1 && !values.messageRouteList.length) {
        return void message.error('关联发布路由不能为空')
      }
      if (!values.templateList.length) {
        return void message.error('关联邮件模板不能为空')
      }
      Modal.confirm({
        title: `确认要${actionName}吗？`,
        onOk: async () => {
          try {
            setSubmitting(true)
            const api = messageId ? apiUpdateMsgList : apiPostMsgManageAdd
            const params = {
              ...values,
              templateId: values.templateList[0]?.templateId,
              routeIds: values.eventType === 2 ? [] : values.messageRouteList.map(item => item.routeId),
            }
            const data = await api(messageId ? { ...params, messageId } : (params as ISendValues))
            if (data.success) {
              message.success(`${actionName}成功`)
              onSuccess?.()
              onHide()
            } else {
              message.error(data.errorMsg)
            }
          } finally {
            setSubmitting(false)
          }
        },
      })
    })

    return (
      <Drawer
        title={`${typeName}消息模板`}
        width={1500}
        open={open}
        onClose={onHide}
        afterOpenChange={afterOpenChange}
        footer={
          <div className={styles.footer}>
            <Space>
              <Button onClick={onHide}>取消</Button>
              <Button type="primary" onClick={() => submitHandler()} disabled={loading} loading={submitting}>
                {actionName}
              </Button>
            </Space>
          </div>
        }
      >
        <div className={styles.detailBox}>
          {loading ? (
            <Loading />
          ) : (
            <div className={styles.main} style={{ display: 'flex' }}>
              <>
                <div className={styles.main_left} ref={scrollRef}>
                  <section id={`${idPrefix}_0`}>
                    <b>基础信息</b>
                    <Divider style={{ margin: '8px 0' }} orientation="center" orientationMargin={0} />
                    {formRender0()}
                  </section>
                  <section id={`${idPrefix}_1`}>
                    <b>触发事件</b>
                    <Divider style={{ margin: '8px 0' }} orientation="center" orientationMargin={0} />
                    {formRender1()}
                  </section>
                  <section id={`${idPrefix}_2`}>
                    <b>通知渠道</b>
                    <Divider style={{ margin: '8px 0' }} orientation="center" orientationMargin={0} />
                    {formRender2()}
                  </section>
                </div>
                <Anchor
                  className={styles.main_right}
                  affix={false}
                  getContainer={() => scrollRef.current || window}
                  onClick={e => e.preventDefault()}
                  items={['基础信息', '触发事件', '通知渠道'].map((name, index) => ({
                    key: name,
                    href: `#${idPrefix}_${index}`,
                    title: name,
                  }))}
                />
              </>
            </div>
          )}
        </div>
      </Drawer>
    )
  },
  {
    open: (props: IAddOrEditMsgDrawerProps) => {
      updatePopup(<AddOrEditMsgDrawer {...props} destroy={() => updatePopup(null)} />)
    },
  },
)
